#!/bin/sh

# set umask correctly.
umask 0002

if /bin/mountpoint -q "${UM_MOUNTPOINT}"; then
  if [ ! -L /media/usb0 ]; then
    RET=0
    if [ -d "${UM_MOUNTPOINT}/measurement" ]; then
      echo "measurement directory already exists"
      RET=1
    else 
      echo "measurement directory not exists"
      # check if /usr/local/sdcard/measurement exists
      # and if so, move it to the usb stick
      if [ -d /usr/local/sdcard/measurement ]; then
        if cp -a /usr/local/sdcard/measurement "${UM_MOUNTPOINT}/"; then
          mv /usr/local/sdcard/measurement /usr/local/sdcard/measurement_bak
          RET=1
        fi
      else
        if ! mkdir "${UM_MOUNTPOINT}/measurement"; then
          echo "error creating measurement directory"
        else 
          echo "measurement directory created successfully"
          RET=1
        fi
      fi
    fi

    # copy all diagram data from the usb stick to the
    # /tmp/measurement path where HMIPServer will store its data
    rm -rf /tmp/measurement
    cp -a "${UM_MOUNTPOINT}/measurement" /tmp/

    if [ ${RET} -eq 1 ]; then

      # make sure /var/status exists with correct permissions
      if [ ! -d /var/status ]; then
        mkdir -p /var/status
        chown root:status /var/status
        chmod 2775 /var/status
      fi

      touch /var/status/USBinitialised
      # CCU2 compatibility
      touch /var/status/SDinitialised

      # link /media/usb0 to the active usb mountpoint
      ln -sfn "${UM_MOUNTPOINT}" /media/usb0
    fi
  fi
fi
